
//
//  ServiceHomeViewController.m
//  HondaPro_2
//
//  Created by glendale on 13-6-9.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "ServiceHomeViewController.h"
#import "repairCell.h"
#import "serviceCell.h"
#import <QuartzCore/QuartzCore.h>
#import "CarCalendarQueryViewController.h"

#import "repairHostoryView.h"

#import "MainMenuDataModel.h"

#import "SVProgressHUD.h"

#import "SearchPartsInventoryViewController.h"

#import "InformationViewController.h"

#import "AddServiceViewController.h"

#import "PdfViewController.h"

#import "VehicleDataEditViewController.h"
#import "WaringInformationViewController.h"

#import "ServiceAssignedViewController.h"
#import "MyAFNetWorkManager.h"
#import "getJobSheetViewController.h"
#import "MJRefresh.h"


#define MM_GET_JOB_MSG_FOR_DISPATCHING_FLAG_         @"mm_getJobMsgForDispatchingFlag";

@interface ServiceHomeViewController ()

@property (weak, nonatomic) IBOutlet UIButton *ishondaBtn;
@property (weak, nonatomic) IBOutlet UIButton *nohondaBtn;

/** 是否在修 */
@property (weak, nonatomic) IBOutlet UIButton *isRepairedBtn;

//维修派工 按钮的回调方法
- (IBAction)paigongBntPressed:(UIButton *)sender;

/** 服务顾问数据列表 */
@property(nonatomic,strong)NSMutableArray *arrDisDataForEvaluator;
@property(nonatomic,strong)NSMutableDictionary *serviceAdviserDic;

/** 车系列表 */
@property(nonatomic,strong)NSMutableArray *carSeriesArr;
@property(nonatomic,strong)NSMutableDictionary *carSeriesDic;

/** 车型列表 */
@property(nonatomic,strong)NSMutableArray *carModelArr;
@property(nonatomic,strong)NSMutableDictionary *carModelDic;

/** 车型列表 */
@property(nonatomic,strong)NSMutableArray *statusArr;
@property(nonatomic,strong)NSMutableDictionary *statusDic;

@end

@implementation ServiceHomeViewController

@synthesize tableViewTitleBgLbl = _tableViewTitleBgLbl;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization        
        //添加标题
        [self createTitle];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //设置tableView的title label 颜色
    self.tableViewTitleBgLbl.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [self.navigationController.navigationBar setHidden:YES];
    
    self.carTypeId = @"< 空 >";
    self.carClassId= @"< 空 >";
    self.evaluatorPersonId= @"< 空 >";
    self.shopIdId =  @"< 空 >";
    self.stateCode = @"< 空 >";
    
    [self carSeriesArr];
    [self carModelArr];
    [self arrDisDataForEvaluator];
    [self statusArr];
    
    self.isHonda =YES;
    
    [self.cartypeListBtn setTitle:@"< 空 >" forState:UIControlStateNormal];
    [self.carClassNameListBtn setTitle:@"< 空 >" forState:UIControlStateNormal];
    [self.evaluatorPersonListBtn setTitle:@"< 空 >" forState:UIControlStateNormal];
    [self.joobStateListBtn setTitle:@"< 空 >" forState:UIControlStateNormal];
    
    self.carJobTableView.dataSource =self;
    self.carJobTableView.delegate = self;
    
    //[self carDetailed];
    //注册消息
    [self addAllObserver];
    
    //设置MJRefresh
    __weak typeof(self.carJobTableView) weekCarJobTable = self.carJobTableView;
    self.carJobTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self searchBtn:nil];
        [weekCarJobTable.mj_header endRefreshing];
    }];
    
    weekCarJobTable.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
       
        [self updateTheAsyCarJobTableView];
        [weekCarJobTable.mj_footer endRefreshing];
    }];
}

/** 转接待传入参数 */
-(void)setTurnServiceParam:(NSDictionary *)turnServiceParam{
    _turnServiceParam = turnServiceParam;

    if (self.turnServiceParam) {
        self.customerName.text = _turnServiceParam[@"CUSTOMER_NAME"];
        [self.carClassNameListBtn setTitle:_turnServiceParam[@"SERIES_NAME"] forState:UIControlStateNormal];
        [self.cartypeListBtn setTitle:_turnServiceParam[@"MODEL_NAME"] forState:UIControlStateNormal];
        [self.evaluatorPersonListBtn setTitle:_turnServiceParam[@"SA_NAME"] forState:UIControlStateNormal];
        self.isRepairedBtn.selected = NO;
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.turnServiceParam) {//转接待操作
        [self turnToMakeJobSheet];
        self.turnServiceParam = nil;
    }else{
        //初始化三个属性值， 车主车辆信息 界面 使用
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        //车架号
        modelIns.currentVinSel = @"";
        //车牌号
        modelIns.strCurrentPlateNumber = @"";
        //车主姓名
        modelIns.strCurrentCustomerName = @"";
        
        strCurrJobSheetId = nil;
        jobCurrtState = nil;
        
        _mmJobSheetRowSel = -1;
        //初始化 维修车历 的选中行标识
        _mmHistoryRowSel = -1;
        
        //刷新表单
        [self searchBtn:nil];
        self.historyArray = nil;
        [self.hostoryView.repairTableView reloadData];
    }
    
}

/** 转接待操作 */
-(void)turnToMakeJobSheet{
    NSMutableDictionary *param = [self getParameters];
    [param removeObjectForKey:@"IS_HONDA"];//移除是否oem参数
    [SVProgressHUD showWithStatus:@"请等待...."];
    
    [MyAFNetWorkManager postWithParam:param andAction:@"QUER_VEHICLE_REPAIR_ORDER" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        if (!error) {
            NSMutableArray *datas = obj[@"TT_REPAIR_ORDER"];
            NSString *msg = nil;
            if (!datas) {
                msg = @"未查询到相关的车主车辆信息";
            }else if (datas.count>1) {
                [self searchUpdataUIWithDatas:datas];
                msg = @"查询多个结果，请选择其中一个操作";
            }            
            
            if (msg) {
                [SVProgressHUD dismiss];
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示信息" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
            
            NSMutableDictionary *selectedData = datas[0];
            NSDictionary *param = @{@"VIN":self.vin.text,@"STATE_NAME":@"12551001"};
            [self makeNewJobSheetWithParam:param selectedData:selectedData];
            
        }else{
            [SVProgressHUD dismiss];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示信息" message:@"查询异常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            NSLog(@"%@",error);
        }
        
    }];
}

#define mark 返回主页
-(IBAction)backBntSelect:(id)sender{
    
    //[self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

//车型
-(IBAction)cartypeListBtn:(id)sender{
    
    if (!contentCon) {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
        contentCon.delegate = self;
    }
    
    contentCon.btnSender=self.cartypeListBtn;
    self.popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    [self.popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [self.popCon setPopoverContentSize:CGSizeMake(self.cartypeListBtn.frame.size.width, 280)];
    [self.popCon presentPopoverFromRect:CGRectMake(40, 15, 120, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    contentCon.list = self.carModelArr;
    [contentCon.myTableView reloadData];
}

//弹出的回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn{
    
    if (btn==self.PrintBtn){
        
        //调用接口
        webService *web=[[webService alloc] init];
        web.methodName = GETPRINTJOBSHEETPDF;
        NSMutableArray *paras=[NSMutableArray arrayWithObjects:@"jobSheetId",strCurrJobSheetId,@"printType",[NSString stringWithFormat:@"%d",row], nil];
        self.PrintType = [NSString stringWithFormat:@"%d",row];
        [web commonGetSharedRequest:GETPRINTJOBSHEETPDF wsparas:paras];
        [SVProgressHUD showWithStatus:@"请等待...."];

        //设置属性
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        modelIns.jobSheetIdForPrint = strCurrJobSheetId;
        modelIns.printTypeForPrint = [NSString stringWithFormat:@"%d",row];
    }
    if (row>0) {
        
        if (btn==self.cartypeListBtn) {
       
            self.carTypeId = [[self.carTypeArray objectAtIndex:row-1] objectForKey:@"carTypeId"];
        }else if (btn==self.carClassNameListBtn){
            self.carClassId = [[self.carClassArray objectAtIndex:row-1] objectForKey:@"carClassCode"];
        }else if (btn==self.evaluatorPersonListBtn){
            self.evaluatorPersonId = [[self.evaluatorPersonArray objectAtIndex:row-1] objectForKey:@"evaluatorPersonId"];
        }else if(btn==self.joobStateListBtn){
            self.stateCode = [[self.stateArray objectAtIndex:row-1] objectForKey:@"stateCode"];
        }
        
    }else{
        NSString *key = nil;
        if (btn==self.cartypeListBtn) {
            
            key = self.carModelArr[row];
        }else if (btn==self.carClassNameListBtn){
            key = self.carSeriesArr[row];
        }else if (btn==self.evaluatorPersonListBtn){
            key = self.arrDisDataForEvaluator[row];
        }else if(btn==self.joobStateListBtn){
            key = self.statusArr[row];
        }
        [btn setTitle:key forState:UIControlStateNormal];
    }
    
    [self.popCon dismissPopoverAnimated:YES];
    self.popCon = nil;
}

//车种名
-(IBAction)carClassNameListBtn:(id)sender{
    
    if (!contentCon) {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
        contentCon.delegate = self;
    }
    
    contentCon.btnSender=self.carClassNameListBtn;
    
    
    self.popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [self.popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [self.popCon setPopoverContentSize:CGSizeMake(self.carClassNameListBtn.frame.size.width, 280)];
    
    [self.popCon presentPopoverFromRect:CGRectMake(40, 15, 120, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    contentCon.list = self.carSeriesArr;
    [contentCon.myTableView reloadData];
}


//作业状态
-(IBAction)joobStateListBtn:(id)sender;{
    
    if (!contentCon) {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
        contentCon.delegate = self;
    }
    
    contentCon.btnSender=sender;
    
    self.popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    //[DDPopoverBackgroundView setShadowEnabled:NO];//关闭箭头
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [self.popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [self.popCon setPopoverContentSize:CGSizeMake(self.evaluatorPersonListBtn.frame.size.width, 280)];
    
    [self.popCon presentPopoverFromRect:CGRectMake(40, 15, 120, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    contentCon.list = self.statusArr;
    [contentCon.myTableView reloadData];
}

//估价人
-(IBAction)evaluatorPersonListBtn:(id)sender{
    
    if (!contentCon) {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
        contentCon.delegate = self;
    }
    
    contentCon.btnSender=sender;
    contentCon.list = self.arrDisDataForEvaluator;
    
    self.popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    //[DDPopoverBackgroundView setShadowEnabled:NO];//关闭箭头
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [self.popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [self.popCon setPopoverContentSize:CGSizeMake(self.evaluatorPersonListBtn.frame.size.width, 280)];
    
    [self.popCon presentPopoverFromRect:CGRectMake(40, 15, 120, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    [contentCon.myTableView reloadData];
    
}


#pragma mark - 查询相关方法
-(IBAction)searchBtn:(id)sender
{
    [self.view endEditing:YES];
    //将车牌号转化为大写
    self.plateNumber.text = [self.plateNumber.text uppercaseString];
    strCurrJobSheetId = nil;
    self.carJobArray = nil;
    self.historyArray = nil;
    _from = 0;
    _to = 10;
    [self queryJobSheet];
}


-(void)queryJobSheet{
    NSMutableDictionary *param = [self getParameters];
    [param setObject:@(_from) forKey:@"FROM"];
    [param setObject:@(_to) forKey:@"TO"];
    [SVProgressHUD showWithStatus:@"请等待...."];
    
    NSString *actionName = self.isRepairedBtn.selected?@"QUERY_REPAIR_ORDER_PAD":@"QUER_VEHICLE_REPAIR_ORDER";
    
    [MyAFNetWorkManager postWithParam:param andAction:actionName finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        [SVProgressHUD dismiss];
        if (!error) {
            NSMutableArray *datas = obj[@"TT_REPAIR_ORDER"];
            [self searchUpdataUIWithDatas:datas];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示信息" message:@"查询异常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            NSLog(@"%@",error);
        }
        
    }];
}

-(void)searchUpdataUIWithDatas:(NSArray *)datas{

    if (datas) {
        //将arrForTmp里边的数据添加进数据模型中
        if (self.carJobArray.count>0)
        {
            NSRange rangge = NSMakeRange(0,datas.count);
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:rangge];
            [self.carJobArray insertObjects:datas atIndexes:indexSet];
        }
        else
        {
            self.carJobArray = [NSMutableArray arrayWithArray:datas];
        }
    }
    
    //刷新表单数据
    [self.carJobTableView reloadData];
    [self.hostoryView.repairTableView reloadData];
}

/** 返回搜索参数 */
-(NSMutableDictionary *)getParameters
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    if ([self.plateNumber.text length] != 0) {
        [param setObject:[self.plateNumber.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"PLATE_NUMBER"];
    }
    
    if ([self.vin.text length] != 0) {
        [param setObject:self.vin.text forKey:@"VIN"];
    }
    if (self.customerName.text&&[self.customerName.text length] != 0){
        [param setObject:[self.customerName.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"CUSTOMER_NAME"];
    }
    NSString *name = self.cartypeListBtn.titleLabel.text;
    if (name &&![name isEqualToString:@"< 空 >"]) {//车型
        [param setObject:self.carModelDic[name] forKey:@"CAR_TYPE_ID"];
    }
    name = self.carClassNameListBtn.titleLabel.text;
    if (name &&![name isEqualToString:@"< 空 >"]) {//车系
        [param setObject:self.carSeriesDic[name] forKey:@"CAR_CLASS_CODE"];
    }
    name = self.evaluatorPersonListBtn.titleLabel.text;
    if (name &&![name  isEqualToString:@"< 空 >"]) {
        [param setObject:self.serviceAdviserDic[name] forKey:@"EVALUATOR_PERSON_ID"];
    }
    name = self.joobStateListBtn.titleLabel.text;
    if (![name isEqualToString:@"< 空 >"])
    {
        [param setObject:self.statusDic[name] forKey:@"STATE_CODE"];
    }
    [param setObject:self.isHonda? @"1":@"0" forKey:@"IS_HONDA"];
    return param;
    
}

- (IBAction)isHondaSelect:(id)sender {
    if (sender==self.ishondaBtn) {
        self.isHonda=YES;
    }else{
        self.isHonda=NO;
    }
    self.ishondaBtn.selected = self.isHonda;
    self.nohondaBtn.selected = !self.isHonda;
}

- (IBAction)isRepairedClicked:(UIButton *)sender {
    sender.selected = !sender.selected;
}

#pragma mark - tableView数据源

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView ==self.carJobTableView) {
        _mmJobSheetRowSel = -1;
       return  [self.carJobArray count];
    }else if (tableView==self.hostoryView.repairTableView){
        //初始化 维修车历 的选中行标识
        _mmHistoryRowSel = -1;
        return [self.historyArray count];
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 42.0f;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger row = [indexPath row];
    if (tableView== self.carJobTableView)
    {
        static NSString *identifier = @"identifier";
        serviceCell *cell = (serviceCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"serviceCell" owner:self options:Nil];
            cell = [nib objectAtIndex:0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleGray;

        if (row<[self.carJobArray count])
        {
            NSDictionary *dic = self.carJobArray[row];
            cell.jobSheetId.text =dic[@"JOB_SHEET_ID"];
            cell.planNumber.text = dic[@"PLATE_NUMBER"];
            cell.vin.text = dic[@"VIN"];
            cell.carSeries.text = [self getNameByCodeWithDic:self.carSeriesDic code:dic[@"SERIES"]];
            cell.carTypeId.text = [self getNameByCodeWithDic:self.carModelDic code:dic[@"MODEL"]];
            cell.custormerName.text = dic[@"CUSTOMER_NAME"];
            cell.evaluatorName.text = [self getNameByCodeWithDic:self.serviceAdviserDic code:dic[@"EVALUATOR_NAME"]];
            if (self.isRepairedBtn.selected) {
                cell.stateName.text = [self getNameByCodeWithDic:self.statusDic code:dic[@"STATE_NAME"]];
            }else{
                cell.stateName.text = dic[@"STATE_NAME"];
            }
            
        }
        else
        {
            cell.jobSheetId.text =@"";
            cell.planNumber.text =@"";
            cell.vin.text =@"";
            cell.carSeries.text =@"";
            cell.carTypeId.text =@"";
            cell.custormerName.text =@"";
            cell.evaluatorName.text =@"";
            cell.stateName.text =@"";
        }
        
        //设置Cell的背景色
        //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
        cell.backgroundColor = [UIColor clearColor];
        switch (row%2)
        {
            case 0:
                //浅灰色
                cell.contentView.backgroundColor = [UIColor colorWithRed:232.0/255.0 green:232.0/255.0 blue:232.0/255.0 alpha:1.0];
                break;
            case 1:
                //浅浅灰色
                cell.contentView.backgroundColor = [UIColor colorWithRed:246.0/255.0 green:246.0/255.0 blue:246.0/255.0 alpha:1.0];
                break;
                
            default:
                break;
        }
        
        return cell;
        
    }
    else if (tableView == self.hostoryView.repairTableView)
    {
        static NSString *identifier = @"repairCell";
        repairCell *cell = (repairCell*) [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"repairCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        
        if (row <[self.historyArray count])
        {
            cell.jobSheetId.text = [[self.historyArray objectAtIndex:row] objectForKey:@"JOB_SHEET_ID"];
            cell.milemeter.text =[[[self.historyArray objectAtIndex:row] objectForKey:@"MILEMETER"] stringValue];
            cell.comingDate.text = [[self.historyArray objectAtIndex:row] objectForKey:@"COMING_DATE"];
            cell.deliverDate.text =[[self.historyArray objectAtIndex:row] objectForKey:@"DELIVERY_DATE"];
        }
        else
        {
            cell.jobSheetId.text = @"";
            cell.milemeter.text = @"";
            cell.comingDate.text = @"";
            cell.deliverDate.text = @"";
        }
        
        //设置Cell的背景色
        //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
        cell.backgroundColor = [UIColor clearColor];
        switch (row%2)
        {
            case 0:
                //浅灰色
                cell.contentView.backgroundColor = [UIColor colorWithRed:232.0/255.0 green:232.0/255.0 blue:232.0/255.0 alpha:1.0];
                break;
            case 1:
                //浅浅灰色
                cell.contentView.backgroundColor = [UIColor colorWithRed:246.0/255.0 green:246.0/255.0 blue:246.0/255.0 alpha:1.0];
                break;
                
            default:
                break;
        }
        
        return cell;
    }
    return nil;
}

-(NSString *)getNameByCodeWithDic:(NSDictionary *)dic code:(id)code{
    NSArray *keys = dic.allKeys;
    for (NSString *key in keys) {
        if ([code isKindOfClass:[NSNumber class]]) {
            NSString *strCode = [code stringValue];
            NSString *val = dic[key];
            if ([val isEqualToString:strCode]) {
                return key;
            }
        }else{
            if ([dic[key] isEqualToString:code]) {
                return key;
            }
        }
        
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView==self.carJobTableView) {
        if ([indexPath row] >= [self.carJobArray count])
        {
            return;
        }
        NSInteger row = [indexPath row];
        
        //得到当前行的车架号调用接口方法1车辆维修历史 接口促进信息提醒；
        NSString *vin = [[self.carJobArray objectAtIndex:row] objectForKey:@"VIN"];
        
        NSDictionary *selectData = self.carJobArray[row];
        _dicJobSheetData = selectData;
        strCurrJobSheetId = selectData[@"JOB_SHEET_ID"];
        if (self.isRepairedBtn.selected) {
            jobCurrtState = [selectData[@"STATE_NAME"]stringValue];
        }else{
            jobCurrtState = selectData[@"STATE_NAME"];
        }
        
        _strCurrVin = vin;
        currtPlateNamber = selectData[@"PLATE_NUMBER"];
        //车架号
        [MainMenuDataModel sharedMainMenuDataModel].currentVinSel = vin;
        //车牌号
        [MainMenuDataModel sharedMainMenuDataModel].strCurrentPlateNumber = currtPlateNamber;
        //车主姓名
        [MainMenuDataModel sharedMainMenuDataModel].strCurrentCustomerName = selectData[@"CUSTOMER_NAME"];
        
        //获取当前作业单对应的车型
        [MainMenuDataModel sharedMainMenuDataModel].strCurrentCarType = selectData[@"MODEL"];
        
        //查询车历
        [self repairBtnSelect:vin];
        
        _mmJobSheetRowSel = indexPath.row;
    }else if (tableView == self.hostoryView.repairTableView)//维修车历的行被选中
    {
        if ([indexPath row] >= [self.historyArray count])
        {
            return;
        }
        //设置选中行的标识
        _mmHistoryRowSel = indexPath.row;
    }
    
}


//车辆维修历史
-(void)repairBtnSelect:(NSString*)vin{
    
    for (UIView *view in [self.repairPanle subviews]) {
        [view removeFromSuperview];
    }
    
    [self.repairPanle addSubview:self.hostoryView];
    
    [SVProgressHUD showWithStatus:@"请等待...."];
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:3];
//    [param setObject:@(0) forKey:@"FROM"];
//    [param setObject:@(10) forKey:@"TO"];
    [param setObject:vin forKey:@"VIN"];
    
    [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_REPAIR_ORDER_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        if (!error) {
            NSMutableArray *datas = (NSMutableArray *)obj[@"TT_REPAIR_ORDER"];
            self.historyArray = datas;
            [self.hostoryView.repairTableView reloadData];
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD dismiss];
            NSLog(@"%@",error);
        }
        
    }];
    
}

-(repairHostoryView *)hostoryView{
    if (_hostoryView == nil) {
        _hostoryView = [[[NSBundle mainBundle] loadNibNamed:@"repairHostoryView" owner:self options:nil] objectAtIndex:0];
        
        [_hostoryView setFrame:CGRectMake(0, 0, self.repairPanle.frame.size.width, self.repairPanle.frame.size.height)];
    }
    return _hostoryView;
}

#pragma mark - 外观检查
-(IBAction)outCheckBntSelect:(id)sender{
    
    if (-1 == _mmHistoryRowSel)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"未选中维修车历选项" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }

    NSString *jobSheetNo = self.historyArray[_mmHistoryRowSel][@"JOB_SHEET_ID"];
    
    NSDictionary *param = @{@"RO_NO":jobSheetNo};;

    [SVProgressHUD showWithStatus:@"请等待...."];
    //查询工单
    [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_REPAIR_ORDER_DETAIL_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        [SVProgressHUD dismiss];
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
            return;
        }else{
            NSMutableDictionary *baseInfo = obj[@"TT_REPAIR_ORDER"][0];

            NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
            [dataDic setObject:baseInfo forKey:@"baseInfo"];//基本信息
            if (obj[@"TT_DEFECT"]) {
                [dataDic setObject:obj[@"TT_DEFECT"] forKey:@"defectList"];//缺陷
            }
            if (obj[@"TT_RO_CONFIRM"]) {
                [dataDic setObject:obj[@"TT_RO_CONFIRM"] forKey:@"goodsConfirm"];//物品确认
            }
            if (obj[@"TT_RO_FILE"]) {
                [dataDic setObject:obj[@"TT_RO_FILE"] forKey:@"fileList"];//图片列表
            }
            
            checkOutViewController *vc = [[checkOutViewController alloc] initWithNibName:@"checkOutViewController" bundle:nil];
            vc.dicOutCheckTmp = dataDic;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];

}

-(IBAction)fectionCheckBntSelect:(id)sender{
    
    for (UIView *view in [self.repairPanle subviews]) {
        [view removeFromSuperview];
    }

}

#pragma mark - 作业单制作
-(IBAction)jobSheetMake:(id)sender
{
    //（1）如果作业单表单选中行为 －1 ，说明没有选中，提示选择作业单，return；
    if (-1 == _mmJobSheetRowSel)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"请选择车辆" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return;
    }

   [SVProgressHUD showWithStatus:@"请等待...."];
    NSMutableDictionary *selectedData = self.carJobArray[_mmJobSheetRowSel];//选中行数据
    if (strCurrJobSheetId == nil || [strCurrJobSheetId isEqualToString:@""]) {//新增
        NSDictionary *param = @{@"VIN":_strCurrVin,@"STATE_NAME":@"12551001"};
        [self makeNewJobSheetWithParam:param selectedData:selectedData];
        
    }else{//修改
        NSDictionary *param = @{@"RO_NO":strCurrJobSheetId,@"VIN":_strCurrVin};
        [self makeJobSheetWithParam:param selectedData:selectedData isNew:false];
    }
    
}

/** 新工单制作 */
-(void)makeNewJobSheetWithParam:(NSDictionary *)param selectedData:(NSMutableDictionary *)selectedData{
    [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_REPAIR_ORDER_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        if (error) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
            return;
        }else{
            NSMutableArray *datas = obj[@"TT_REPAIR_ORDER"];
            if (datas&&datas.count>0) {
                [SVProgressHUD dismiss];
                UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"信息提示" message:@"该车架号已经存在在修工单" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alerVeiw show];
                return;
            }
            [self makeJobSheetWithParam:param selectedData:selectedData isNew:YES];
        }
        
    }];
}

-(void)makeJobSheetWithParam:(NSDictionary *)param selectedData:(NSMutableDictionary *)selectedData isNew:(BOOL)isNew{
    __weak MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
    
    [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_REPAIR_ORDER_DETAIL_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        [SVProgressHUD dismiss];
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
            return;
        }else{
            getJobSheetViewController *getJobSheetCon = [[getJobSheetViewController alloc] initWithNibName:@"getJobSheetViewController" bundle:nil];
            NSMutableArray *arr = obj[@"TM_VEHICLE"];//预交款
            NSDictionary *predic = arr[0];
            if (isNew) {
                [selectedData setObject:selectedData[@"OWNER_NO"] forKey:@"OWNER_NO"];
                [selectedData setObject:selectedData[@"CUSTOMER_NAME"] forKey:@"OWNER_NAME"];
                if (predic[@"PRE_PAY"]) {
                    [selectedData setObject:predic[@"PRE_PAY"] forKey:@"PRE_PAY"];//预交款
                }
                
                mainModel.dicBaseMessage = selectedData;
                mainModel.arrOutCheck = nil;//缺陷
                mainModel.repairProjects = nil;//维修项目
                mainModel.partList = nil;//零件
                mainModel.attachProjects = nil;//附加项目
                mainModel.arrCarryGoods = nil;//物品确认
                mainModel.arrImageList = nil;//图片列表
                getJobSheetCon.optType = operationTypeAdd;
            }else{
                NSMutableDictionary *baseInfo = obj[@"TT_REPAIR_ORDER"][0];
                if (predic[@"PRE_PAY"]) {
                    [baseInfo setObject:predic[@"PRE_PAY"] forKey:@"PRE_PAY"];
                }
                id curMileage = predic[@"CURRENT_MILEAGE"];
                [baseInfo setObject:curMileage?curMileage:@"0" forKey:@"CURRENT_MILEAGE"];
                mainModel.dicBaseMessage = baseInfo;//基本信息
                mainModel.arrOutCheck = obj[@"TT_DEFECT"];//缺陷
                mainModel.repairProjects = obj[@"TT_RO_LABOUR"];//维修项目
                mainModel.partList = obj[@"TT_RO_REPAIR_PART"];//零件
                mainModel.attachProjects = obj[@"TT_RO_ADD_ITEM"];//附加项目
                mainModel.arrCarryGoods = obj[@"TT_RO_CONFIRM"];//物品确认
                mainModel.arrImageList = obj[@"TT_RO_FILE"];//图片列表
                NSString *statusCode = [NSString stringWithFormat:@"%@",[selectedData[@"STATE_NAME"]stringValue]];
                getJobSheetCon.optType = [statusCode isEqualToString:@"12551010"]?operationTypeView:operationTypeModify;
            }
            mainModel.deletedRepairProjects = nil;
            mainModel.deletedPartList = nil;
            mainModel.deletedAttachProjects = nil;
            mainModel.arrOutCheckDeleted = nil;
            mainModel.nRowForRepairItemList = -1;
            mainModel.nRowForPartList = -1;
            mainModel.nRowForOtherChargeList = -1;
            mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
            picDataModel.arrForNewImage = nil;
            [self.navigationController pushViewController:getJobSheetCon animated:YES];
        }
    }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag==1111) {
        
        if (buttonIndex==1) {

        }else{
            return;
        }
    }
}


// 车历查询
- (IBAction)carCalendarQueryBtnPressed:(UIButton *)sender
{
//    NSLog(@"carCalendarQueryBtnPressed!!!");
    //（1）判断是否选中作业单，如果没有选中，提示 未选中作业单，return
    if (nil == strCurrJobSheetId)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"未选中作业单！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    //（2）判断该辆车是否有维修车历，如果没有，提示 没有维修车历 ，return
    if (0 == [self.historyArray count])
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"该车没有维修车历！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    CarCalendarQueryViewController *vc = [[CarCalendarQueryViewController alloc] initWithNibName:@"CarCalendarQueryViewController" bundle:nil];
    vc.allHistory = self.historyArray;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 创建标题

-(void)createTitle
{
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(170, 20, 120, 50)];
    lbl.textColor = [HelpClass colorWithHexString:@"666666"];
    lbl.font = [UIFont systemFontOfSize:26];
    lbl.text = @"接待服务";
    [self.view addSubview:lbl];
}


//打印操作
- (IBAction)pritSselect:(id)sender {
    
    //
    NSArray *stateArray = [NSArray arrayWithObjects:@"估价确认",@"估价打印",@"等待派工",@"待料",@"等待答复",@"零件预订",@"进入钣金",@"离开钣金",@"进入喷漆",@"离开喷漆",@"进入修理",@"离开修理",@"完工检查",@"反完工",@"清洗", nil];
    NSArray *stateArray2 = [NSArray arrayWithObjects:@"结算",@"会计打印", nil];
    if (strCurrJobSheetId!=Nil) {
        NSArray *printArray= [[NSArray alloc] init];
//        NSLog(@"%@",jobCurrtState);
//        NSLog(@"%i",[jobCurrtState length]);
//        NSLog(@"%i",[jobCurrtState rangeOfString:@"零件预定"].length);
//        
//        if (4 == [jobCurrtState rangeOfString:@"零件预定"].length)
//        {
//            printArray = [NSArray arrayWithObjects:@"预览估价单",@"预览作业单", nil];
//        }
        
        if ([stateArray indexOfObject:jobCurrtState]!=NSNotFound) {
            printArray = [NSArray arrayWithObjects:@"预览估价单",@"预览作业单", nil];
//            NSLog(@"tttmm=11==%@",printArray);
            
        }else if([stateArray2 indexOfObject:jobCurrtState]!=NSNotFound){
            printArray = [NSArray arrayWithObjects:@"预览估价单",@"预览作业单",@"预览结算单",@"预览会计帐票",@"预览车历卡", nil];
//            NSLog(@"tttmm=22==%@",printArray);
        }else if ([jobCurrtState isEqualToString:@"估价"]){
            return;
        }
        
        
        
        if (!contentCon) {
            contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
        }
        contentCon.delegate = self;
        contentCon.btnSender=sender;
        
        contentCon.list = printArray;
        
        self.popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
        [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
        [DDPopoverBackgroundView setArrowBase:30.0];//箭头
        [DDPopoverBackgroundView setArrowHeight:15.0];
        //[DDPopoverBackgroundView setShadowEnabled:NO];//关闭箭头
        [DDPopoverBackgroundView setContentInset:1.0];
        
        [self.popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
        [self.popCon setPopoverContentSize:CGSizeMake(self.evaluatorPersonListBtn.frame.size.width, 200)];
        
        [self.popCon presentPopoverFromRect:CGRectMake(4, 15, 80, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
        [contentCon.myTableView reloadData];
    }
}

-(void)getPrintPdf:(NSNotification *)notification{
    
    NSData *pdfData = (NSData*)notification.object;
    
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"print.pdf"];
    //先删除除已存在的文件
    NSFileManager *defaulManager = [NSFileManager defaultManager];
    [defaulManager removeItemAtPath:fullPath error:nil];
    // 将图片写入文件
    if ([pdfData writeToFile:fullPath atomically:YES]) {
        
        //调用接口
        webService *web=[[webService alloc] init];
        web.methodName = GETBARCODEIMAGEFORCODE39;
        NSMutableArray *paras=[NSMutableArray arrayWithObjects:@"jobSheetId",strCurrJobSheetId,@"printType",self.PrintType, nil];
        /*
         default:
         fontSize=26,
         width=389,
         height=31
         */
        
//        [paras addObject:@"fontSize"];
//        [paras addObject:[NSString stringWithFormat:@"%i",MM_CODE_39_FONT_SIZE_]];
//        [paras addObject:@"width"];
//        [paras addObject:[NSString stringWithFormat:@"%i",MM_CODE_39_WIDTH_]];
//        [paras addObject:@"height"];
//        [paras addObject:[NSString stringWithFormat:@"%i",MM_CODE_39_HEIGHT_]];
        
        [web commonGetSharedRequest:GETBARCODEIMAGEFORCODE39 wsparas:paras];
        
//        PdfViewController *pdfCon= [[PdfViewController alloc] initWithNibName:@"PdfViewController" bundle:nil];
//        [self.navigationController pushViewController:pdfCon animated:YES];
//        
//        [SVProgressHUD dismiss];
//
    }
}

-(void)getBarCode39Img:(NSNotification *)notification{
    
    NSData *imgData = (NSData*)notification.object;
    
    /*cun image to document*/
    UIImage *image_fuck = [UIImage imageWithData:imgData];
    NSString *filePath_fuck = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"明明条形码.png"]];   // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(image_fuck) writeToFile: filePath_fuck    atomically:YES]; // 保存成功会返回YES
    NSLog(@"%i",result);
    
    
    
    
    
    CGPDFDocumentRef pdf;
    
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSURL *url = [NSURL fileURLWithPath:path];
    
    CFURLRef pdfURL = CFBundleCopyResourceURLInDirectory((CFURLRef)(__bridge void *)(url), CFSTR("print.pdf"), nil, nil);
    pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
    CFRelease(pdfURL);

    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"print.pdf"];
    
    
    size_t count = CGPDFDocumentGetNumberOfPages (pdf);// 3
    
    NSLog(@"%zu",count);
    
    if (count == 0) {
//        NSLog(@"PDF needs at least one page");
        return;
    }
    
    
    CGRect paperSize = CGRectMake(0.0,0.0,595,841);
    UIGraphicsBeginPDFContextToFile( fullPath, paperSize, nil);//将pdf写如文件
    
    for (int i=1; i<=count; i++)
    {
        UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
        CGContextRef currentContext = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
        CGContextScaleCTM(currentContext, 1.0, -1.0);
        CGPDFPageRef page = CGPDFDocumentGetPage (pdf, i);
        CGContextDrawPDFPage (currentContext, page);
        
        if (1 == i)
        {
            UIImage *image = [UIImage imageWithData:imgData];
            CGImageRef pageImage = [image CGImage];
            CGContextDrawImage(currentContext, CGRectMake(15,773,250 , 25), pageImage);//绘制图片309 31
        }
    }
    
//    UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
//    CGContextRef currentContext = UIGraphicsGetCurrentContext(); // flip context so page is right way up
//    CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
//    CGContextScaleCTM(currentContext, 1.0, -1.0);
//    CGPDFPageRef page = CGPDFDocumentGetPage (pdf, 1); // grab page 1 of the PDF
//    CGContextDrawPDFPage (currentContext, page); // draw page 1 into graphics context // flip context so annotations are right way up
//    
//    
//    UIImage *image = [UIImage imageWithData:imgData];
//    
//    CGImageRef pageImage = [image CGImage];
//    
//    CGContextDrawImage(currentContext, CGRectMake(15,773,250 , 25), pageImage);//绘制图片309 31
//
//    if (count > 1)
//    {
//        
//        
//        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 595, 841), nil);
//        CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
//        CGContextScaleCTM(currentContext, 1.0, -1.0);
//        CGPDFPageRef page2 = CGPDFDocumentGetPage (pdf, 2); // grab page 1 of the PDF
//        CGContextDrawPDFPage (currentContext, page2); // draw page 1 into graphics context // flip context so annotations are right way up
//    }
    
    
    
    UIGraphicsEndPDFContext();
    
    
    CGPDFDocumentRelease (pdf);
    
    
    
    PdfViewController *pdfCon= [[PdfViewController alloc] initWithNibName:@"PdfViewController" bundle:nil];
    [self.navigationController pushViewController:pdfCon animated:YES];
    
    [SVProgressHUD dismiss];
    
}


//车主车辆
- (IBAction)carCustomerSelect:(id)sender
{
    InformationViewController *ivv = [[InformationViewController alloc]initWithNibName:@"InformationViewController" bundle:nil];
    if (_mmJobSheetRowSel>-1) {
       ivv.customerParamOut = self.carJobArray[_mmJobSheetRowSel];;
    }
    
    [self.navigationController pushViewController:ivv animated:YES];
    [ivv informationHomeBackButton];
    //remove observer
}
//零件查询
- (IBAction)partSearchSelect:(id)sender {
    //进行界面跳转
    SearchPartsInventoryViewController *vc = [[SearchPartsInventoryViewController alloc] initWithNibName:@"SearchPartsInventoryViewController" bundle:nil];
    [vc replaceHomeBtnByBAckBtn];
    [self.navigationController pushViewController:vc animated:YES];
}
//增值服务
- (IBAction)addServiceSelect:(id)sender {
    AddServiceViewController* viewController = [[AddServiceViewController alloc] initWithNibName:@"AddServiceViewController" bundle:nil];
    [self.navigationController pushViewController:viewController animated:YES];
    
}


//注册消息
-(void)addAllObserver
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPrintPdf:) name:GETPRINTJOBSHEETPDF object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getBarCode39Img:) name:GETBARCODEIMAGEFORCODE39 object:nil];

}


//刷新数据的方法
-(void)updateTheAsyCarJobTableView
{
    _from += 10;
    _to += 10;
    [self queryJobSheet];
}


#pragma mark -车辆详情
-(IBAction)carDetailedBtn:(id)sender
{
    if(_strCurrVin == nil)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请选择作业单！" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        return;
    }
    InformationViewController *ivv = [[InformationViewController alloc]initWithNibName:@"InformationViewController" bundle:nil];
    ivv.carParamOut = @{
                        @"PLATE_NUMBER":currtPlateNamber,
                        @"vin":_strCurrVin
                        };
    [self.navigationController pushViewController:ivv animated:YES];
    [ivv informationHomeBackButton];
}

#pragma mark - textField delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.plateNumber
        ||
        textField == self.vin)
    {
        textField.keyboardType = UIKeyboardTypeAlphabet;
    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.plateNumber)
    {
        //将车牌号转化为大写
        self.plateNumber.text = [self.plateNumber.text uppercaseString];
    }
    
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == self.plateNumber)
    {
        //将车牌号转化为大写
        self.plateNumber.text = [self.plateNumber.text uppercaseString];
    }
}

- (IBAction)orderPartsBtnPressed:(UIButton *)sender
{
    /*
     http://10.251.68.91/DMS/PAD/OrderRepairParts.aspx?jobSheetId=H201309010001
     */
    //调用接口
        
    if ([strCurrJobSheetId isEqualToString:@""]
        ||
        strCurrJobSheetId == nil)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"请选择一个作业单" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return;
    }
    NSMutableArray *arrTmp = [NSMutableArray array];
    [arrTmp addObject:@"jobSheetId"];
    [arrTmp addObject:strCurrJobSheetId];
    
}


- (IBAction)san_bao_BtnPressed:(UIButton *)sender
{
    //进行界面跳转
    WaringInformationViewController *vc = [[WaringInformationViewController alloc] initWithNibName:@"WaringInformationViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)paigongBntPressed:(UIButton *)sender
{
    //（1）如果作业单表单选中行为 －1 ，说明没有选中，提示选择作业单，return；
    if (-1 == _mmJobSheetRowSel)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"请选择车辆" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alerVeiw show];
        
        return;
    }
    
    NSLog(@"%@",_dicJobSheetData);
    
    if ([[_dicJobSheetData objectForKey:@"stateName"] isEqualToString:@"估价"]
        ||
        [[_dicJobSheetData objectForKey:@"stateName"] isEqualToString:@"估价确认"])
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"本作业单不可进行派工" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alerVeiw show];
        
        return;
    }
    
    NSMutableArray *arrTmp = [NSMutableArray array];
    [arrTmp addObject:@"jobSheetId"];
    [arrTmp addObject:strCurrJobSheetId];
}


-(void)invokePromoteListByVin:(NSString *)vinFormPara
{
   
}


- (IBAction)wanGongJianChanBtn:(id)sender
{
    //（1）如果作业单表单选中行为 －1 ，说明没有选中，提示选择作业单，return；
    if (-1 == _mmJobSheetRowSel)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"请选择车辆" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alerVeiw show];
        
        return;
    }
    else
    {

        //调用webservice get方法
        webService *web=[[webService alloc] init];
        web.methodName = GETJOBSHEET;
        
        NSMutableArray *paras=[NSMutableArray arrayWithObjects:@"jobSheetId",strCurrJobSheetId, nil];
        
        [web commonGetSharedRequest:GETJOBSHEET wsparas:paras];
        
        [SVProgressHUD showWithStatus:@"请等待...."];
    }
    
    

    
}
- (IBAction)zhongTuLiChangBtn:(id)sender
{
    if (-1 == _mmJobSheetRowSel)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"请选择车辆" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alerVeiw show];
        
        return;
    }
    else
    {
        
        //调用webservice get方法
        webService *web=[[webService alloc] init];
        web.methodName = GETJOBSHEET;
        
        NSMutableArray *paras=[NSMutableArray arrayWithObjects:@"jobSheetId",strCurrJobSheetId, nil];
        
        [web commonGetSharedRequest:GETJOBSHEET wsparas:paras];
        
        [SVProgressHUD showWithStatus:@"请等待...."];
    }
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

#pragma mark - 下拉框数据懒加载
/** 服务顾问 */
-(NSMutableArray *)arrDisDataForEvaluator{
    if (_arrDisDataForEvaluator == nil) {
        _arrDisDataForEvaluator= [NSMutableArray array];
        _serviceAdviserDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"SERVICE_ADVISOR"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_arrDisDataForEvaluator addObject:name];
            [_serviceAdviserDic setObject:val forKey:name];
        }
    }
    return _arrDisDataForEvaluator;
}

-(NSMutableArray *)carSeriesArr{
    if (_carSeriesArr == nil) {
        _carSeriesArr= [NSMutableArray array];
        _carSeriesDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"SERIES"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"SERIES_NAME"];
            NSString *val = dic[@"SERIES_CODE"];
            [_carSeriesArr addObject:name];
            [_carSeriesDic setObject:val forKey:name];
        }
    }
    return _carSeriesArr;
}

-(NSMutableArray *)carModelArr{
    if (_carModelArr == nil) {
        _carModelArr= [NSMutableArray array];
        _carModelDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"MODEL"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"MODEL_NAME"];
            NSString *val = dic[@"MODEL_CODE"];
            [_carModelArr addObject:name];
            [_carModelDic setObject:val forKey:name];
        }
    }
    return _carModelArr;
}

-(NSMutableArray *)statusArr{
    if (_statusArr == nil) {
        _statusArr= [NSMutableArray array];
        _statusDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_RO_STATUS"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_statusArr addObject:name];
            [_statusDic setObject:val forKey:name];
        }
    }
    return _statusArr;
}

@end
